package com.chenyun.boot.web.controller;


import com.chenyun.common.constants.SysConstants;
import com.chenyun.common.exceptions.BusinessException;
import com.chenyun.common.exceptions.CommonException;
import com.chenyun.common.utils.StringUtils;
import com.chenyun.common.vo.AjaxResult;
import com.chenyun.common.vo.ResultCode;
import com.chenyun.common.vo.ServiceResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.UndeclaredThrowableException;


@ControllerAdvice
@Order(200)
public class ControllerAdviceHandler {
    Logger logger = LoggerFactory.getLogger(ControllerAdviceHandler.class);

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public AjaxResult error(HttpServletRequest request, HttpServletResponse response, Exception e) {
        e.printStackTrace();
        rollbackGlobal();
        if (e.getClass() == CommonException.class) {
            //类型转型
            CommonException ce = (CommonException) e;
            if (ce.getResultCode()==null){
                return AjaxResult.FAIL(ce.getMessage());
            }
            AjaxResult ajaxResult = new AjaxResult(ce.getResultCode());
            return ajaxResult;
        }
        return AjaxResult.ERROR(e.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public Object businessException(HttpServletRequest request, HttpServletResponse response,BusinessException ex) {
        String header = request.getHeader(SysConstants.T_REQUEST_ID);
        if (StringUtils.isNotBlank(header)){
            //不等于空 标识是feign请求 返回 serviceResponse
            return ServiceResponse.fail(ex.getMessage());
        }else {
            if (ex.getResultCode()!=null){
               return new AjaxResult(ex.getResultCode(),ex.getMessage());
            }
            if (ex.getCodeEnum()!=null){
                return new AjaxResult(Integer.valueOf(ex.getCodeEnum().getErrorCode()),ex.getCodeEnum().getErrorMsg(),false);
            }
            return new AjaxResult(ResultCode.FAIL,ex.getMessage());
        }

    }
    @ResponseBody
    @ExceptionHandler(value = UndeclaredThrowableException.class)
    public AjaxResult undeclaredThrowableException(UndeclaredThrowableException ex) {
        return AjaxResult.FAIL(ex.getUndeclaredThrowable().getMessage());
    }

//    @ResponseBody
//    @ExceptionHandler(value = InvalidScopeException.class)
//    public AjaxResult validInvalidScopeException(InvalidScopeException ex) {
//        return AjaxResult.FAIL("不支持此访问范围的scope");
//    }

    /**
     * 实体验证失败错误捕捉
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult validError(MethodArgumentNotValidException ex) {
        ex.printStackTrace();
        BindingResult bindingResult = ex.getBindingResult();
        //只要进入此方法一定会报错
        String defaultMessage = bindingResult.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.ERROR(defaultMessage);

    }

    /**
     * 参数绑定异常
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public AjaxResult handleBindException(BindException e) {
        logger.error("参数绑定异常:" + e.getBindingResult());
        return AjaxResult.ERROR(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }


//    @ResponseBody
//    @ExceptionHandler(value = {IbatisException.class, UncategorizedSQLException.class})
//    public AjaxResult validError(Exception ex) throws TransactionException {
//        ex.printStackTrace();
//        rollbackGlobal();
//        return AjaxResult.FAIL("数据库业务执行失败!");
//
//    }


    /**
     * 回滚seata的全局事务
     */
    private void rollbackGlobal() {

//        //获取事务id
//        String xid = RootContext.getXID();
//        if (!StringUtils.isEmpty(xid)) {
//            logger.info("开始回滚分布式事务,事务id:{}",xid);
//            System.out.println("开始回滚分布式事务,事务id:"+xid);
//            //回滚事务
//            GlobalTransactionContext.reload(xid).rollback();
//            logger.info("结束回滚分布式事务,事务id:{}",xid);
//            System.out.println("结束回滚分布式事务,事务id:"+xid);
//
//        }
    }


}
